<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { useMerchantStore } from "@/store";
import {
  getStoreOrderStats,
  getStoreReviewStats,
  getStoreTopProducts,
} from "@/api/index";
import { ElMessage, ElEmpty } from "element-plus";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";
import StarRating from "@/components/common/StarRating.vue";

const merchantStore = useMerchantStore();

// 后续API数据
const storeInfo = reactive({
  name: "",
  status: "",
  rating: 0,
  salesToday: 0,
  ordersToday: 0,
  pendingOrders: 0,
});
const recentOrders = ref<any[]>([]);

// 评价统计
const reviewStats = ref<{ average: number; total: number }>({
  average: 0,
  total: 0,
});
// 商品销量前十
const topProducts = ref<any[]>([]);

// 促销活动
const promotions = ref<any[]>([]);

// 加载状态
const loading = ref(false);
const isOverallLoading = ref(false); // 添加整体加载状态

// 更新店铺状态
const updateStoreStatus = async (status: string, isManual = false) => {
  try {
    // 检查状态是否真的改变了
    if (status === storeInfo.status) {
      return; // 如果状态没有变化，不执行更新操作
    }

    // 只有在手动切换时才调用API更新状态
    if (isManual) {
      if (
        merchantStore.storeInfo.status === "PENDING" ||
        merchantStore.storeInfo.status === "SUSPENDED"
      ) {
        ElMessage.warning("当前店铺状态不允许更改营业状态。");
        return;
      }

      // 将前端状态值转换为API需要的状态值
      const apiStatus = status === "open" ? "OPEN" : "CLOSED";
      console.log("更新店铺状态:", apiStatus);

      const { updateStoreStatus } = await import("@/api/merchant"); // 直接从 merchant.ts 导入
      await updateStoreStatus(merchantStore.currentStoreId, {
        status: apiStatus,
        storeStatus: apiStatus,
        state: apiStatus,
      });

      // 更新store中的状态，设置为true抑制通知，避免显示重复消息
      merchantStore.updateStoreStatus(apiStatus, true);

      // 直接在这里显示消息
      ElMessage.success(
        `店铺已${apiStatus === "OPEN" ? "开启营业" : "关闭营业"}`
      );

      // 同步本地状态
      storeInfo.status = status;
    } else {
      // 非手动操作，只同步状态，不调用API，不显示提示
      storeInfo.status =
        merchantStore.storeInfo.status === "OPEN" ? "open" : "closed";
    }
  } catch (error) {
    console.error("更新店铺状态失败", error);
    if (isManual) {
      // 恢复之前的状态
      storeInfo.status = storeInfo.status === "open" ? "closed" : "open";
      ElMessage.error("状态更新失败");
    }
  }
};

// 加载仪表盘数据
const loadDashboardData = async () => {
  if (!merchantStore.currentStoreId) return;

  loading.value = true;
  isOverallLoading.value = true; // 设置整体加载状态

  try {
    // 确保抑制状态更新通知
    merchantStore.suppressStatusNotification = true;

    // 从store中获取数据，避免重复设置触发监听
    storeInfo.name = merchantStore.storeInfo.name;

    // 直接赋值状态，不触发状态更新逻辑
    // 将API状态值转换为前端状态值
    storeInfo.status =
      merchantStore.storeInfo.status === "OPEN" ? "open" : "closed";
    console.log(
      "仪表盘加载时的店铺状态:",
      merchantStore.storeInfo.status,
      "->",
      storeInfo.status
    );

    storeInfo.rating = merchantStore.storeInfo.rating || 0;

    // 获取今日销售额、订单数、待处理订单
    const today = new Date();
    const yyyy = today.getFullYear();
    const mm = String(today.getMonth() + 1).padStart(2, "0");
    const dd = String(today.getDate()).padStart(2, "0");
    const startDate = `${yyyy}-${mm}-${dd}`;
    const endDate = startDate;

    // 动态 import 相关API
    const {
      getStoreOrderStats,
      getOrders, // 更名为 getOrders
      getStoreReviewStats,
      getStoreTopProducts,
      listPromotions, // 更名为 listPromotions
      getPlatformStatistics,
    } = await import("@/api/index");

    // 获取统计数据
    try {
      const statsRes = await getPlatformStatistics(merchantStore.currentStoreId,{startDate,endDate});
      // 确保从正确的数据结构中获取数据
      let data: any = null;
      if (statsRes.data && statsRes.data.data) {
        data = statsRes.data.data;
      } else if (statsRes.data) {
        data = statsRes.data;
      }

      console.log("店铺统计数据:", data);

      if (data) {
        // 使用API返回的字段名称
        storeInfo.salesToday = data.todaySales || 0;
        storeInfo.ordersToday = data.todayOrderCount || 0;
        // 初始化待处理订单数量
        storeInfo.pendingOrders = 0;
        reviewStats.value.average = data.reviewStatistics.averageRating || 0;
        reviewStats.value.total = data.reviewStatistics.totalReviews || 0;
                // 使用API返回的hotFoods结构
        topProducts.value = data.hotFoods.map((item: any) => ({
          id: item.foodId,
          name: item.foodName,
          image: item.foodImage,
          sales: item.saleCount,
          amount: item.saleAmount,
        }));
      }
    } catch (error) {
      console.error("获取订单统计失败", error);
    }

    // 获取订单数据（一次性获取足够多的订单用于统计和展示）
    try {
      const ordersRes = await getOrders(merchantStore.currentStoreId, {
        page: 1,
        size: 50, // 获取足够多的订单数据用于统计和展示
      });
      console.log("订单数据:", ordersRes);
      const orders =
        ordersRes.data?.data?.content || ordersRes.data?.data || ordersRes.data;
      
      if (Array.isArray(orders)) {
        // 设置最近订单（只展示已完成的订单，取前5条）
        const completedOrders = orders.filter(order => 
          order.status === 'COMPLETED' || order.status === 'completed'
        );
        recentOrders.value = completedOrders.slice(0, 5);
        
        // 统计待处理订单数量
        storeInfo.pendingOrders = orders.filter(order => 
          order.status === 'PENDING' || order.status === 'pending'
        ).length;
      } else {
        recentOrders.value = [];
        storeInfo.pendingOrders = 0;
      }
    } catch (error) {
      console.error("获取订单数据失败", error);
      recentOrders.value = [];
      storeInfo.pendingOrders = 0;
    }

    // 促销活动
    try {
      const promoRes = await listPromotions(merchantStore.currentStoreId); // 使用 listPromotions
      const promo = promoRes.data?.data || promoRes.data;
      promotions.value = Array.isArray(promo) ? promo : promo?.list || [];
    } catch (error) {
      console.error("获取促销活动失败", error);
    }
  } catch (error) {
    console.error("加载数据失败", error);
  } finally {
    loading.value = false;
    isOverallLoading.value = false; // 清除整体加载状态
  }
};

onMounted(async () => {
  // 确保加载店铺信息
  if (merchantStore.stores.length === 0) {
    await merchantStore.fetchStores(true); // 抑制通知
  }

  // 如果有当前选中的店铺，加载数据
  if (merchantStore.currentStoreId) {
    loadDashboardData();
  }
});

// 监听店铺变化
watch(
  () => merchantStore.currentStoreId,
  (newStoreId) => {
    if (newStoreId) {
      // 重置状态，避免触发状态更新
      storeInfo.status = "";
      // 确保抑制状态更新通知
      merchantStore.suppressStatusNotification = true;
      loadDashboardData();
    }
  }
);

// 添加对store中状态变化的监听
watch(
  () => merchantStore.storeInfo.status,
  (newStatus) => {
    if (newStatus) {
      console.log("监听到店铺状态变化:", newStatus);
      // 更新前端显示状态
      if (newStatus === "OPEN" || newStatus === "CLOSED") {
        storeInfo.status = newStatus === "OPEN" ? "open" : "closed";
      }
    }
  },
  { immediate: true } // 立即执行一次
);
</script>

<template>
  <merchant-layout>
    <div v-loading="isOverallLoading">
      <!-- 无店铺时显示提示 -->
      <div v-if="!merchantStore.currentStoreId" class="no-store-tip">
        <el-empty description="请先选择或创建一个店铺" :image-size="200">
          <el-button type="primary" @click="$router.push('/merchant/store')">
            创建店铺
          </el-button>
        </el-empty>
      </div>

      <!-- 有店铺时显示仪表盘 -->
      <div v-else class="dashboard-content">
        <!-- 数据卡片 -->
        <div class="data-cards">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card shadow="hover" class="data-card-wrapper" v-loading="loading">
                <div class="data-card">
                  <div class="data-icon sales">
                    <el-icon>
                      <Money />
                    </el-icon>
                  </div>
                  <div class="data-info">
                    <div class="data-title">今日销售额</div>
                    <div class="data-value">
                      <template v-if="loading">
                        <el-skeleton :rows="1" animated />
                      </template>
                      <template v-else> ¥{{ storeInfo.salesToday }} </template>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>

            <el-col :span="8">
              <el-card shadow="hover" class="data-card-wrapper" v-loading="loading">
                <div class="data-card">
                  <div class="data-icon orders">
                    <el-icon>
                      <Tickets />
                    </el-icon>
                  </div>
                  <div class="data-info">
                    <div class="data-title">今日订单数</div>
                    <div class="data-value">
                      <template v-if="loading">
                        <el-skeleton :rows="1" animated />
                      </template>
                      <template v-else>
                        {{ storeInfo.ordersToday }}
                      </template>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>

            <el-col :span="8">
              <el-card shadow="hover" class="data-card-wrapper" v-loading="loading">
                <div class="data-card">
                  <div class="data-icon pending">
                    <el-icon>
                      <Timer />
                    </el-icon>
                  </div>
                  <div class="data-info">
                    <div class="data-title">待处理订单</div>
                    <div class="data-value">
                      <template v-if="loading">
                        <el-skeleton :rows="1" animated />
                      </template>
                      <template v-else>
                        {{ storeInfo.pendingOrders }}
                      </template>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 店铺信息和最近订单 -->
        <el-row :gutter="20" class="dashboard-row">
          <!-- 店铺信息 -->
          <el-col :span="8">
            <el-card shadow="hover" class="store-info-card" v-loading="loading">
              <template #header>
                <div class="card-header">
                  <span>店铺信息</span>
                </div>
              </template>
              <div class="store-info">
                <div class="store-name">
                  <el-avatar v-if="merchantStore.storeInfo.logo" :src="merchantStore.storeInfo.logo" :size="40"
                    style="margin-right: 10px; vertical-align: middle" />
                  <template v-if="loading">
                    <el-skeleton :rows="1" animated />
                  </template>
                  <template v-else>
                    {{ storeInfo.name }}
                  </template>
                </div>
                <div class="store-status">
                  <div class="status-label">店铺状态：</div>
                  <div class="status-content">
                    <template v-if="loading">
                      <el-skeleton :rows="1" animated style="width: 100px" />
                    </template>
                    <template v-else>
                      <el-tag :type="storeInfo.status === 'open' ? 'success' : 'info'" effect="light"
                        style="margin-right: 10px">
                        {{ storeInfo.status === "open" ? "营业中" : "已关闭" }}
                      </el-tag>
                      <el-switch v-model="merchantStore.storeInfo.status" active-value="OPEN" inactive-value="CLOSED"
                        active-color="#13ce66" inactive-color="#ff4949" @change="
                          (val) =>
                            updateStoreStatus(
                              val === 'OPEN' ? 'open' : 'closed',
                              true
                            )
                        " :disabled="merchantStore.storeInfo.status === 'PENDING' ||
                          merchantStore.storeInfo.status === 'SUSPENDED'
                          " />
                    </template>
                  </div>
                </div>
                <div class="store-rating">
                  <div class="rating-label">店铺评分</div>
                  <div class="rating-stars">
                    <template v-if="loading">
                      <el-skeleton :rows="1" animated />
                    </template>
                    <template v-else>
                      <star-rating :score="storeInfo.rating" :precision="1" />
                    </template>
                  </div>
                </div>
                <div class="store-reviews">
                  <div class="reviews-label">评价数量</div>
                  <div class="reviews-count">
                    <template v-if="loading">
                      <el-skeleton :rows="1" animated />
                    </template>
                    <template v-else>
                      {{ reviewStats.total }}
                    </template>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 最近订单 -->
          <el-col :span="16">
            <el-card shadow="hover" class="recent-orders-card" v-loading="loading">
              <template #header>
                <div class="card-header">
                  <span>最近订单</span>
                  <el-button text type="primary" @click="$router.push('/merchant/orders')" :disabled="loading">
                    查看全部
                  </el-button>
                </div>
              </template>
              <div class="recent-orders">
                <template v-if="loading">
                  <el-skeleton :rows="5" animated />
                </template>
                <template v-else>
                  <el-table :data="recentOrders" style="width: 100%">
                    <el-table-column prop="id" label="订单号" width="120" />
                    <el-table-column prop="customerName" label="顾客" width="120" />
                    <el-table-column prop="totalAmount" label="金额" width="100" align="right">
                      <template #default="scope">
                        ¥{{ scope.row.totalAmount }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="scope">
                        <el-tag :type="scope.row.status === 'pending'
                            ? 'warning'
                            : scope.row.status === 'completed'
                              ? 'success'
                              : scope.row.status === 'cancelled'
                                ? 'danger'
                                : 'info'
                          " size="small">
                          {{
                            scope.row.status === "pending"
                              ? "待处理"
                              : scope.row.status === "processing"
                                ? "处理中"
                                : scope.row.status === "completed"
                                  ? "已完成"
                                  : scope.row.status === "cancelled"
                                    ? "已取消"
                                    : scope.row.status
                          }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" label="下单时间" />
                  </el-table>
                  <div v-if="recentOrders.length === 0" class="no-data">
                    <el-empty description="暂无订单" :image-size="80" />
                  </div>
                </template>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 热门商品和促销活动 -->
        <el-row :gutter="20" class="dashboard-row">
          <!-- 热门商品 -->
          <el-col :span="12">
            <el-card shadow="hover" class="top-products-card" v-loading="loading">
              <template #header>
                <div class="card-header">
                  <span>热门商品</span>
                  <el-button text type="primary" @click="$router.push('/merchant/products')" :disabled="loading">
                    管理商品
                  </el-button>
                </div>
              </template>
              <div class="top-products">
                <template v-if="loading">
                  <el-skeleton :rows="5" animated />
                </template>
                <template v-else>
                  <el-table :data="topProducts" style="width: 100%">
                    <el-table-column prop="name" label="商品名称" />
                    <el-table-column prop="price" label="价格" width="100" align="right">
                      <template #default="scope">
                        ¥{{ scope.row.price }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="salesCount" label="销量" width="100" align="right" />
                  </el-table>
                  <div v-if="topProducts.length === 0" class="no-data">
                    <el-empty description="暂无数据" :image-size="80" />
                  </div>
                </template>
              </div>
            </el-card>
          </el-col>

          <!-- 促销活动 -->
          <el-col :span="12">
            <el-card shadow="hover" class="promotions-card" v-loading="loading">
              <template #header>
                <div class="card-header">
                  <span>促销活动</span>
                  <el-button text type="primary" @click="$router.push('/merchant/promotions')" :disabled="loading">
                    管理活动
                  </el-button>
                </div>
              </template>
              <div class="promotions">
                <template v-if="loading">
                  <el-skeleton :rows="5" animated />
                </template>
                <template v-else>
                  <el-table :data="promotions" style="width: 100%">
                    <el-table-column prop="name" label="活动名称" />
                    <el-table-column prop="type" label="类型" width="100">
                      <template #default="scope">
                        {{
                          scope.row.type === "discount"
                            ? "折扣"
                            : scope.row.type === "reduction"
                              ? "满减"
                              : scope.row.type
                        }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="scope">
                        <el-tag :type="scope.row.status === 'active'
                            ? 'success'
                            : scope.row.status === 'upcoming'
                              ? 'warning'
                              : 'info'
                          " size="small">
                          {{
                            scope.row.status === "active"
                              ? "进行中"
                              : scope.row.status === "upcoming"
                                ? "即将开始"
                                : scope.row.status === "expired"
                                  ? "已结束"
                                  : scope.row.status
                          }}
                        </el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div v-if="promotions.length === 0" class="no-data">
                    <el-empty description="暂无活动" :image-size="80" />
                  </div>
                </template>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </merchant-layout>
</template>

<style scoped>
.no-store-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 70vh;
  background-color: var(--bg-main);
}

.dashboard-content {
  padding: 20px 0;
  background-color: var(--bg-main);
}

.dashboard-row {
  margin-top: 20px;
}

.data-cards {
  margin-bottom: 20px;
}

.data-card-wrapper {
  height: 120px;
  overflow: hidden;
}

.data-card {
  display: flex;
  align-items: center;
  height: 100%;
}

.data-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 64px;
  height: 64px;
  border-radius: 16px;
  margin-right: 16px;
  font-size: 24px;
}

.data-icon.sales {
  background-color: rgba(255, 213, 79, 0.2);
  color: var(--primary);
}

.data-icon.orders {
  background-color: rgba(33, 150, 243, 0.2);
  color: var(--info);
}

.data-icon.pending {
  background-color: rgba(255, 152, 0, 0.2);
  color: var(--warning);
}

.data-info {
  flex: 1;
}

.data-title {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.data-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.store-info-card,
.recent-orders-card,
.top-products-card,
.promotions-card {
  height: 100%;
}

.store-info {
  padding: 16px 0;
}

.store-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.store-status {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  justify-content: space-between;
}

.status-label {
  color: var(--text-secondary);
  font-size: 14px;
}

.status-content {
  display: flex;
  align-items: center;
}

.store-rating,
.store-reviews {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rating-label,
.reviews-label {
  color: var(--text-secondary);
}

.reviews-count {
  font-weight: 600;
  font-size: 16px;
}

.no-data {
  padding: 20px 0;
  display: flex;
  justify-content: center;
}

.ml-2 {
  margin-left: 8px;
}
</style>
